package com.cf.service.impl;

import com.cf.entity.Power;
import com.cf.entity.Role;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cf.dao.PowerDao;
import com.cf.dao.RoleDao;
import com.cf.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PowerDao powerDao;
    @Override
    public List<Role> selectRoles() {
        return roleDao.selectRoles();
    }

    @Override
    public PageInfo<Role> selectRolesByName(int pagenum, int pagesize, Map map) {
        PageHelper.startPage(pagenum,pagesize);
        List<Role> roles = roleDao.selectRolesByName(map);
        //以业务逻辑的形式从数据库中把当前角色所属的二级菜单查询到放入到对应的一级菜单中
        for (int i=0;i<roles.size();i++){
            Role role = roles.get(i);
            //遍历所有的一级菜单
            for (int j=0;j<role.getChildren().size();j++){
                //当前菜单的每一个一级菜单
                Power p = role.getChildren().get(j);
                //根据一级菜单编号和角色编号来查询旗下的所有的二级菜单集合
                List<Power> powers = powerDao.selectTwoPowerByRidAndPid(role.getRoleid(), p.getPowerid());
                //把二级分类交给其所属的一级分类
                p.setChildren(powers);
            }
        }
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return pageInfo;
    }

    @Override
    public int deletePowerByRoleId(long rid) {
        return roleDao.deletePowerByRoleId(rid);
    }

    @Override
    public int updateRoleAndPower(long rid, String pids) {
        int i = roleDao.deletePowerByRoleId(rid);
        int num = 0;
        if (i!=0){
            String[] split = pids.split(",");
            for (String s:split){
                num = roleDao.addRoleAndPower(rid,Long.parseLong(s));
            }
        }
        return num;
    }

    @Override
    public int addRoleAndPower(long rid, long powerid) {
        return roleDao.addRoleAndPower(rid,powerid);
    }

    @Override
    public List<Role> selectByUserId(long id) {
        return roleDao.selectByUserId(id);
    }

    @Override
    public int deleteRole(long roleid) {
        return roleDao.deleteRole(roleid);
    }
    @Override
    public int updateById(Role role) {
        return roleDao.updateById(role);
    }

    @Override
    public Role selectByRoleid(long roleid) {
        return roleDao.selectByRoleid(roleid);
    }

}
